package main.controller;

import main.GlobalConfig;
import main.RequestHelper;
import main.TimeHelper;
import main.database.AccountHelper;
import main.database.ArticleHelper;
import main.database.AuthorHelper;
import main.database.NotifyHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class SearchResultController {
    @RequestMapping(value = "/search")
    public String doSearch(@RequestParam String key, ModelMap modelMap, HttpServletRequest request) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        boolean exist = AccountHelper.isExistFromUUID(uuid);
        boolean isAdmin = AccountHelper.isAdminFromUUID(uuid);

        List<String[]> authorList = AuthorHelper.findAuthors(key);
        List<String[]> articleList = ArticleHelper.findArticles(key);
        int searchResultCount = authorList.size() + articleList.size();

        modelMap.put("searchResultCount", searchResultCount);
        modelMap.put("year2year", TimeHelper.getFormattedYear2Year());
        modelMap.put("isLogin", exist);
        modelMap.put("isAdmin", isAdmin);

        String resultUrl = "noContentInSearchPage";
        modelMap.put("name", key);

        long unread = NotifyHelper.countUnreadNotify(uuid);
        modelMap.put("authorList", authorList);
        modelMap.put("articleList", articleList);
        modelMap.put("unread", unread);
        modelMap.put("siteName", GlobalConfig.siteName);

        if (searchResultCount > 0) {
            resultUrl = "searchResultPage";
        }

        return resultUrl;
    }
}
